#!/usr/bin/env python
# -*- coding: utf-8 -*-
from app import app
from flask import jsonify, request
from models.email_sender import Email_sender
from models.email_reciver import Email_recier
from bson import ObjectId
from utils import common
from flask_login import login_required
import datetime
from utils.zhuang_shi import timer
from utils.sendReportEmail import send_report_email


#邮件发送人相关
@timer
@app.route('/api/testEmailSender', methods=['POST'])
@login_required
def testEmailSender():
    global mail_namelist
    username = request.get_json()["username"]
    password = request.get_json()["password"]
    mail_namelist = username
    title = '测试'
    content = '测试'
    if send_report_email(username, password, mail_namelist, title, content, attachment=None):
        return jsonify({"data": "\u9a8c\u8bc1\u901a\u8fc7 (*^\u25bd^*) \u60a8\u53ef\u4ee5\u653e\u5fc3\u300c\u63d0\u4ea4\u300d\u4e86", "status": "ok"})
    else:
        return jsonify({"data": "\u9a8c\u8bc1\u5931\u8d25 o(\u2565\ufe4f\u2565)o", "status": "failed"})



@timer
@app.route('/api/project/<project_id>/mailSenderList', methods=['GET'])
@login_required
def mailSenderList(project_id):
    total_num, projects = common.get_total_num_and_arranged_data(Email_sender, request.args, fuzzy_fields=['name'])
    return jsonify({'status': 'ok', 'data': {'totalNum': total_num, 'rows': projects}})


@timer
@app.route('/api/project/<project_id>/addMailSender', methods=['POST'])
@login_required
def addMailSender(project_id):
    try:
        request.get_json()["status"] = True
        request.get_json()["createAt"] = datetime.datetime.utcnow()
        request.get_json()["lastUpdateTime"] = datetime.datetime.utcnow()
        request.get_json()["projectId"] = ObjectId(project_id)
        filtered_data = Email_sender.filter_field(request.get_json(), use_set_default=True)
        Email_sender.insert(filtered_data)
        return jsonify({'status': 'ok', 'data': '新建成功'})
    except BaseException as e:
        return jsonify({'status': 'failed', 'data': '新建失败 %s' % e})


#邮件接收人相关
@timer
@app.route('/api/project/<project_id>/mailList', methods=['GET'])
@login_required
def mailList(project_id):
    total_num, projects = common.get_total_num_and_arranged_data(Email_recier, request.args, fuzzy_fields=['name'])
    return jsonify({'status': 'ok', 'data': {'totalNum': total_num, 'rows': projects}})



@timer
@app.route('/api/project/<project_id>/addMail', methods=['POST'])
@login_required
def addMail(project_id):
    try:
        request.get_json()["status"] = True
        request.get_json()["createAt"] = datetime.datetime.utcnow()
        request.get_json()["lastUpdateTime"] = datetime.datetime.utcnow()
        request.get_json()["projectId"] = ObjectId(project_id)
        filtered_data = Email_recier.filter_field(request.get_json(), use_set_default=True)
        Email_recier.insert(filtered_data)
        return jsonify({"data": "\u65b0\u5efa\u6210\u529f", "status": "ok"})
    except BaseException as e:
        return jsonify({'status': 'failed', 'data': '新建失败 %s' % e})

@timer
@app.route('/api/project/<project_id>/mailList/<mail_id>/updateMail', methods=['POST'])
@login_required
def updateMail(project_id,mail_id):
    try:
        filtered_data = Email_recier.filter_field(request.get_json())
        for key, value in filtered_data.items():
            Email_recier.update({"_id": ObjectId(mail_id)},
                           {'$set': {key: value}})
        update_response = Email_recier.update({"_id": ObjectId(mail_id)},
                                         {'$set': {'lastUpdateTime': datetime.datetime.utcnow()}}, )
        if update_response["n"] == 0:
            return jsonify({'status': 'failed', 'data': '未找到相应更新数据！'})
        return jsonify({"data": "\u66f4\u65b0\u6210\u529f",  "status": "ok"}
)
    except BaseException as e:
        return jsonify({'status': 'failed', 'data': '更新失败: %s' % e})